from django.shortcuts import render, redirect
from web import models
from utils.tencent.cos import delete_bucket


def setting(request, project_id):
    return render(request, 'setting.html')


def setting_delete(request, project_id):
    if request.method == "GET":
        return render(request, 'setting_delete.html')
    # 获取删除的项目名
    project_name = request.POST.get('project_name')
    # 判断是否为空且是否为当前创建者的项目
    if not project_name or project_name != request.tracer.project.name:
        return render(request, 'setting_delete.html', {'error': '项目名错误'})
    # 判断当前用户是否为创建者(创建者才有权限删除)
    if request.tracer.user != request.tracer.project.creator:
        return render(request, 'setting_delete.html', {'error': '只有创建者可删除项目'})

    # 一.删除项目需要删除桶
    #          -1.删除桶中的文件
    #          -2.删除桶中的文件碎片
    # 二.删除项目
    delete_bucket(request.tracer.project.bucket, request.tracer.project.region)
    models.Project.objects.filter(id=project_id).delete()
    return redirect('project_list')
